package com.yuezhu.versionup;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 * 执行下载任务
 *
 *
 */
public class DownloadTask extends Thread {

	private Context mContext;
	private DownloadInfoTask mInfo;
	private Handler mHandler;// 消息处理器

	private int state = DownloadState.DOWNLOADING;

	private String mUuid;
	public DownloadTask(Context context, DownloadInfoTask info, Handler handler, String uuid) {
		this.mContext = context;
		this.mInfo = info;
		this.mHandler = handler;
		this.mUuid = uuid;
	}

	@SuppressWarnings("resource")
	@Override
	public void run() {
		if(null == mInfo){
			return;
		}
		String urlStr = mInfo.getUrl();
		HttpURLConnection connection = null;
		RandomAccessFile randomAccessFile = null;
		InputStream is = null;
		try {
			//Thread current = Thread.currentThread();
			// 准备数据
			int startPos = mInfo.getStartPos();
			int compeleteSize = mInfo.getCompeleteSize();
			URL url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(30000);
			connection.setReadTimeout(30000);
			connection.setRequestMethod("GET");

			// 设置范围，格式为Range：bytes x-y;
			connection.setRequestProperty("Range", "bytes=" + (startPos + compeleteSize) + "-" + mInfo.getEndPos());

			System.out.println(mInfo.getThreadId()+" threadid liu game perform downloading connection range"
					+" "+"bytes=" + (startPos + compeleteSize) + "-" + mInfo.getEndPos());

			randomAccessFile = new RandomAccessFile(mInfo.getLocalFullPath(), "rwd");
			System.out.println(is+" liu game perform downloading randomFile="
					+randomAccessFile);
			if(randomAccessFile!=null){
				randomAccessFile.seek(startPos + compeleteSize);
				// 将要下载的文件写到保存在保存路径下的文件中
				is = connection.getInputStream();
				System.out.println(" liu game perform downloading startPos"
						+" "+startPos+" "+compeleteSize);
				if(is!=null){
					byte[] buffer = new byte[4096];
					int length = -1;
					while ((length = is.read(buffer)) != -1) {
						System.out.println(mInfo.getThreadId()+" threadid liu game perform downloading length:"
								+length);
						randomAccessFile.write(buffer, 0, length);
						compeleteSize += length;

						// 用消息将下载信息传给进度条，对进度条进行更新
						Message message = Message.obtain();
						message.what = DownloadState.DOWNLOADING;
						//message.obj = urlStr;
						message.obj = mInfo.getTaskId();
						message.arg1 = length;
						mHandler.sendMessage(message);

						//System.out.println("liu game sendmessage downloading...");

						// 暂停状态
						if (state == DownloadState.PAUSE || state == DownloadState.REMOVE){
							randomAccessFile.close();
							return;
						}
					}
					System.out.println("liu game perform downloading over");
				}
				//mCountDownLatch.countDown();
			}
			System.gc();
		} catch (Exception e) {
			Log.d("liu game 下载异常", e.getMessage()+"");
			Message message = Message.obtain();
			message.what = DownloadState.ERROR;
			//message.obj = urlStr;
			message.obj = mInfo.getTaskId();
			mHandler.sendMessage(message);
		} finally{
			//移除队列
			ActivityTaskQueue.getInst().remove(mUuid);
		}
	}

	public void setState(int state) {
		Log.d("状态", state+"");
		this.state = state;
		if(state != DownloadState.PAUSE){
			synchronized (this) {
				notify();
			}
		}
	}

	public Context getmContext() {
		return mContext;
	}

	public void setmContext(Context mContext) {
		this.mContext = mContext;
	}
}
